﻿Public Class fb
    Public Class Project

#Region " Backing Fields "

        Private _project_id As Integer

        Private _name As String

        Private _client_id As Integer

        Private _rate As Double

        Private _description As String

    #End Region

        Public Property project_id() As Integer

            Get

                Return _project_id

            End Get

            Set(ByVal value As Integer)

                _project_id = value

            End Set

        End Property

        Public Property name() As String

            Get

                Return _name

            End Get

            Set(ByVal value As String)

                _name = value

            End Set

        End Property

        Public Property client_id() As Integer

            Get

                Return _client_id

            End Get

            Set(ByVal value As Integer)

                _client_id = value

            End Set

        End Property

        Public Property rate() As Double

            Get

                Return _rate

            End Get

            Set(ByVal value As Double)

                _rate = value

            End Set

        End Property

        Public Property description() As String

            Get

                Return _description

            End Get

            Set(ByVal value As String)

                _description = value

            End Set

        End Property

    End Class

    Public Class ProjectList

        Inherits System.ComponentModel.BindingList(Of Project)

    End Class



    Public Class ProjectFactory

        ''' <summary>

        ''' Gets all employees for a given last name

        ''' </summary>

        Public Shared Function Fill() As ProjectList

            Dim projectList As New ProjectList()

            Return ConvertRowsToList(xml.fbGetTable("project.list", "project"))

        End Function

        ''' <summary>

        ''' Gets all employees

        ''' </summary>

        ' Public Shared Function GetProjects(ByVal project_id As String) As ProjectList

        '    employeesDataTable = _employeesTableAdapter.GetData()

        '   Return ConvertRowsToList(employeesDataTable)

        'End Function


        ''' <summary>

        ''' Internal method for converting rows to employee entities

        ''' </summary>

        Private Shared Function ConvertRowsToList(ByVal ProjectDataTable As fbXml.ProjectDataTable) As ProjectList

            Dim projectList As New ProjectList()

            For Each projectRow As fbXml.ProjectRow In ProjectDataTable

                Dim newProject As New Project()

                With newProject

                    ' use the typed row as the accessor for each column

                    .project_id = projectRow.project_id

                    .name = projectRow.name

                    .client_id = projectRow.client_id

                    .rate = projectRow.rate

                    .description = projectRow.description

                End With

                projectList.Add(newProject)

            Next

            Return projectList

        End Function

    End Class

    Public Class xml
        Public Shared Function fbGetTable(ByVal fbMethod As String, ByVal fbTable As String) As System.Data.DataTable
            Cursor.Current = Cursors.WaitCursor
            Dim fbUrl As String = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\FreshMobile\", "fbUrl", "freshbooksmobile.freshbooks.com")
            Dim fbToken As String = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\FreshMobile\", "fbToken", "123")
            Dim response As System.Net.HttpWebResponse
            Dim request As System.Net.HttpWebRequest

            Dim fbApiUrl As String = "https://" & fbUrl & "/api/2.1/xml-in"
            Dim postData As String = "<?xml version=""1.0"" encoding=""utf-8""?><request method=""" & fbMethod & """><per_page>50</per_page></request>"
            Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData)

            ' Set Credentials Cache
            Dim myCred As New System.Net.NetworkCredential(fbToken, "foo", "")
            Dim credCache As New System.Net.CredentialCache()
            credCache.Add(New Uri("https://" & fbUrl), "Basic", myCred)

            request = DirectCast(System.Net.WebRequest.Create(fbApiUrl), System.Net.HttpWebRequest)
            request.Credentials = credCache
            request.UserAgent = "FreshMobile 1.0"
            request.Method = "POST"
            request.ContentType = "application/xml"
            request.ContentLength = byteArray.Length
            request.AllowWriteStreamBuffering = True
            request.PreAuthenticate = True
            request.Timeout = 10000
            request.KeepAlive = True
            request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy()

            Try

                'GetStream and Encode PostData
                Dim dataStream As System.IO.Stream = request.GetRequestStream()
                dataStream.Write(byteArray, 0, byteArray.Length)
                dataStream.Close()


                ' Set Response
                response = DirectCast(request.GetResponse(), System.Net.HttpWebResponse)
                Dim receiveStream As System.IO.Stream = response.GetResponseStream()
                Dim readStream As New System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8)

                'Create new dataset and load xml from stream
                Dim ds As New System.Data.DataSet
                ds.ReadXml(readStream)

                If Not ds.Tables("response").Rows(0)("status") = "ok" Then Throw New Exception("Freshbooks API Update Error:" & vbCrLf & ds.Tables("response").Rows(0)("error"))

                'close connections
                receiveStream.Close()
                readStream.Close()
                response.Close()

                Return ds.Tables(fbTable)
                ds = Nothing

            Catch ex As Exception
                Cursor.Current = Cursors.Default
                MsgBox(ErrorToString, MsgBoxStyle.Exclamation, "Data Request Error")
                request = Nothing
                Return Nothing
            End Try
        End Function
    End Class
End Class
